package com.foogui.primary.sync;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 实现线程的按照顺序进行执行
 */
public class CustomizedTicket {
    private int count =10;
    int flag=1;
    private final Lock lock=new ReentrantLock();

    private final Condition condition=lock.newCondition();

    public void print3() throws InterruptedException {
        lock.lock();
        try {
            while (flag!=1) condition.await();
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName()+"打印了"+i+"次");
            }
            flag=2;
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void print4() throws InterruptedException {
        lock.lock();
        try {
            while (flag!=2) condition.await();
            for (int i = 0; i < 4; i++) {
                System.out.println(Thread.currentThread().getName()+"打印了"+i+"次");
            }
            flag=3;
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
    public void print5() throws InterruptedException {

        lock.lock();
        try {
            while (flag!=3) condition.await();
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"打印了"+i+"次");
            }
            flag=1;
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public static class Demo{
        public static void main(String[] args) {
            CustomizedTicket ticket = new CustomizedTicket();
            new Thread(()->{
                for (int i = 0; i < 3; i++) {
                    try {
                        ticket.print3();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },"A").start();

            new Thread(()->{
                for (int i = 0; i < 3; i++) {
                    try {
                        ticket.print4();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },"B").start();

            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    try {
                        ticket.print5();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },"C").start();
        }
    }
}
